<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller
{
	private $m_dataObj;
	
	public function __construct()
	{
		parent::__construct();		
		$this->m_dataObj = new DataObject();
	}
	
	public function index()
	{				
		$blogObj = new BlogObject();
		$user = null;
		
		// Validation rules, moved to separate file
		
		// Check if logged on, rank and if validation succeeds
		// Insert blogpost
		if($this->login_model->IsLoggedIn())
		{
			$user = $this->login_model->GetUser();
			if($user->GetRank() > 0)
			{
				if(!$this->form_validation->run() == FALSE)
				{
					$this->blog_model->post_new_blogpost($user->GetUserId(),getBlogHeadline(),getBlogMessage());
				}
			}
		}
		
		// Pagination
		// Trim
		$startRow = $this->uri->segment(3);
		$perPage = 4;		
		if(trim($startRow) == '')
		{
			$startRow = 0;
		}
		
		// Initialize config with determined perPage rows and totalrows
		// Create pagination links and save
		if($rows = $this->blog_model->get_all_blogposts_rows())
		{				
			$config['base_url'] = base_url() . index_page() . getBlogBaseUrl();
			$config['total_rows'] = $rows;
			$config['per_page'] = 4;
			
			$this->pagination->initialize($config);
			$blogObj->SetBlogPages($this->pagination->create_links());
			$blogObj->SetBlogposts($this->blog_model->get_blog_limited($startRow, $perPage));
		}
			
		// Generate smileys
		$image_array = get_clickable_smileys(base_url().'assets/images/smileys/smileys/', 'message');
		$col_array = $this->table->make_columns($image_array, 8);
		$blogObj->SetSmileys($this->table->generate($col_array));

		
		$this->m_dataObj->SetInformation($blogObj);
		$this->m_dataObj->SetContent(getBlogViewUrl());
		$this->m_dataObj->SetTitle(getBlogViewTitle());
		$this->m_dataObj->SetUser($user);
	
		$this->load->view(index_page(), array($this->m_dataObj->GetName() => $this->m_dataObj));
	}
	
	public function comments()
	{
		$blogObj = new BlogObject();
		$blogId = $this->uri->segment(3);
		
		// Validation rules, moved to separate file
		
		// Check if logged, retrieve user
		// Insert new comment
		if($this->login_model->IsLoggedIn())
		{
			$user = $this->login_model->GetUser();
			if(!$this->form_validation->run() == FALSE)
			{
				$this->blog_model->post_new_blog_comment($blogId,$user->GetRank(),getBlogMessage());
			}	
		}
		
		// Retrives blogpost, related comments
		if($blogId != null)
		{		
			$blogObj->SetBlogposts($this->blog_model->get_single_blogpost($blogId));
			$blogObj->SetComments($this->blog_model->get_blogpost_comments($blogId));
			
			$this->m_dataObj->SetInformation($blogObj);
		}
		
		$this->m_dataObj->SetTitle(getBlogViewCommentsTitle());
		$this->m_dataObj->SetContent(getBlogViewCommentsUrl());
		
		$this->load->view(index_page(), array($this->m_dataObj->GetName() => $this->m_dataObj));
	}
}